﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wox.Plugin.Everything.Everything;
using System.IO;

namespace WoxUnityPlugin
{
    class UnityProjectFinder
    {
        public float refreshInterval = 60;

        public string log = "";

        private System.DateTime refreshTime = DateTime.Now;
        private Dictionary<string, string> projects = new Dictionary<string, string>();

        public UnityProjectFinder()
        {
            Refresh();
        }

        private void Refresh()
        {
            refreshTime = DateTime.Now;
            projects.Clear();

            EverythingApiDllImport.Everything_SetMatchPath(false);
            EverythingApiDllImport.Everything_SetSearchW("ProjectVersion.txt");

            EverythingApiDllImport.Everything_QueryW(true);

            var r = EverythingApiDllImport.Everything_GetNumResults();

            var pathSB = new StringBuilder(2048);

            //log = "Refresh";
            for (int i = 0; i < r; ++i)
            {
                EverythingApiDllImport.Everything_GetResultFullPathNameW(i, pathSB, pathSB.Capacity);

                var path = pathSB.ToString();
                //log += path +"\n";

                if (path.EndsWith("ProjectSettings/ProjectVersion.txt")
                    || path.EndsWith("ProjectSettings\\ProjectVersion.txt"))
                {
                    var dir = Path.GetDirectoryName(Path.GetDirectoryName(path));

                    if (Directory.Exists(dir + "/Assets"))
                    {
                        var version = UnityLancher.UnityLancherCore.GetVersion(dir);
                        projects.Add(dir, version);
                    }
                }
            }
        }

        public Dictionary<string, string> GetAllProjects()
        {
            if ((DateTime.Now - refreshTime).TotalSeconds > 60)
            {
                Refresh();
            }

            return projects;
        }
    }
}
